package com.itheima.aop;

import com.itheima.annotation.OperationLog;
import com.itheima.domain.pojo.OperateLog;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

@Component
@Aspect
@Slf4j
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.annotation.OperationLog)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        log.info("环绕通知，准备开始记录日志...");
        //记录开始时间
        long begin = System.currentTimeMillis();
        //调用目标方法
        Object result = pjp.proceed();
        //记录结束时间
        long end = System.currentTimeMillis();
        //创建日志对象
        OperateLog operateLog = new OperateLog();
        // 获取当前登录员工id
        Integer currentEmpId = UserContext.getCurrentEmpId();
        log.info("当前线程:{}", Thread.currentThread().getName());
        operateLog.setOperateEmpId(currentEmpId);
        operateLog.setOperateTime(LocalDateTime.now());//操作时间
        String className = pjp.getTarget().getClass().getName();
        operateLog.setClassName(className); //目标对象的全类名
        String methodName = pjp.getSignature().getName();
        operateLog.setMethodName(methodName);//目标方法名
        Object[] args = pjp.getArgs();
        operateLog.setMethodParams(Arrays.toString(args)); //目标方法的参数
        operateLog.setReturnValue(result.toString());
        operateLog.setCostTime(end - begin);
        //保存日志到数据库表
        //优化：起一个异步线程执行
        operateLogMapper.insert(operateLog);
        return result;
    }

}
